LINQ to XML - Experiences and Exemplars


LINQ, LINQ to XML, .NET Framework 4.0
LINQ, LINQ to XML, XML, Search, Console Window, XML Documentation, Join Operators, Ordering Operators
Desktop, Data
en-US
6/28/2011

Introduction

These samples demonstrate some ways to use LINQ to XML to join, filter, order, search, etc.

Building the Sample

  1. Open Program.cs
  2. Uncomment the line for the sample that you want to run; comment ones you don't want to run
  3. Press Ctrl + F5

Screenshot

Sample Code

C#
Edit|Remove
            [Category("XMP - Experiences and Exemplars")] 
            [Description(@"List the titles and years of all books published by Addison-Wesley after 1991, in alphabetic order.")] 
            public void Q7() 
            { 
                XDocument bib = XDocument.Load("bib.xml"); 
 
                var result = new XElement("bib", 
                                 from b in bib.Descendants("book") 
                                 where (string)b.Element("publisher") == "Addison-Wesley" && 
                                       (int)b.Attribute("year") > 1991 
                                 orderby (string)b.Element("title") 
                                 select new XElement("book", 
                                            b.Attribute("year"), 
                                            b.Element("title"))); 
 
                Console.WriteLine(result); 
 
                // Solution in XQuery: 
                // <bib> 
                // { 
                //    for $b in doc(""http://bstore1.example.com/bib.xml"")//book 
                //    where $b/publisher = ""Addison-Wesley"" and $b/@year > 1991 
                //    order by $b/title 
                //    return 
                //        <book> 
                //            { $b/@year } 
                //            { $b/title } 
                //        </book> 
                // } 
                // </bib> 
            }

Source Code Files

More Information

For more information on LINQ to XML: http://msdn.microsoft.com/en-us/library/bb387098.aspx